package mk.com.it.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @author ristes
 * 
 */
public class DisplayFeeds extends Activity {

	private static final int POSTS_DIALOG = 1;
	static final private int MENU_UPDATE = Menu.FIRST;
	static final private int MENU_PREFERENCES = Menu.FIRST + 1;

	private List<RssPost> posts = new ArrayList<RssPost>();
	private ListView displayFeedListView;
	private DefaultArrayAdapter aa;

	private RssPost selectedPost;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.latest);

		displayFeedListView = (ListView)findViewById(R.id.latest_list_view);

		displayFeedListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView _av, View _v, int _index,
					long arg3) {
				selectedPost = posts.get(_index);
				showDialog(POSTS_DIALOG);
			}
		});

		int layoutID = R.layout.post_list_item;
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		aa = new DefaultArrayAdapter(this, layoutID, posts, vi);
		displayFeedListView.setAdapter(aa);
		// updateFromPreferences();
	}
	
	private void addNewPost(RssPost _post) {
		posts.add(_post);
		// Notify the array adapter of a change.
		aa.notifyDataSetChanged();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, MENU_UPDATE, Menu.NONE, "update");

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case (MENU_UPDATE): {
			refreshEarthquakes();
			return true;
		}
		}
		return false;
	}

	void refreshEarthquakes() {
		// Get the XML
		URL url;
		try {
			String quakeFeed = getString(R.string.feed_uri);
			url = new URL(quakeFeed);

			URLConnection connection;
			try {
				connection = url.openConnection();
				
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				int responseCode = httpConnection.getResponseCode();

				if (responseCode == HttpURLConnection.HTTP_OK) {
					InputStream in = httpConnection.getInputStream();
					readXml(in);
				}
			} catch (IOException ex) {
				System.out.println(ex);
				InputStream in = getResources().openRawResource(R.raw.feed);
				readXml(in);
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} finally {
		}
	}

	private void readXml(InputStream in) throws ParserConfigurationException,
			SAXException, IOException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();

		// Parse the earthquake feed.
		Document dom = db.parse(in);
		Element docEle = dom.getDocumentElement();

		// Clear the old earthquakes
		posts.clear();

		// Get a list of each earthquake entry.
		NodeList nl = docEle.getElementsByTagName("item");
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {
				RssPost post = new RssPost();
				// get the post element
				Element entry = (Element) nl.item(i);
				// handle the title
				Element title = (Element) entry.getElementsByTagName("title")
						.item(0);
				String titleString = title.getFirstChild().getNodeValue();
				post.setTitle(titleString);
				// handle the date
				Element when = (Element) entry.getElementsByTagName("pubDate")
						.item(0);

				String dt = when.getFirstChild().getNodeValue();
				String[] res = dt.split(" ");
				String pubDate = res[1] + " " + res[2] + " " + res[3];
				post.setPubDate(pubDate);

				// handle the link
				Element link = (Element) entry.getElementsByTagName("link")
						.item(0);
				String linkString = link.getFirstChild().getNodeValue();
				post.setLink(new URL(linkString));

				addNewPost(post);

			}
		}
	}

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case (POSTS_DIALOG):
			LayoutInflater li = LayoutInflater.from(this);
			View quakeDetailsView = li.inflate(R.layout.quake_details, null);

			AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this);
			quakeDialog.setTitle("Quake Time");
			quakeDialog.setView(quakeDetailsView);
			return quakeDialog.create();
		}
		return null;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case (POSTS_DIALOG):
			String postPreview = selectedPost.getTitle() + "\n"
					+ selectedPost.getLink().toString() + "\n"
					+ selectedPost.getPubDate();

			AlertDialog quakeDialog = (AlertDialog) dialog;
			quakeDialog.setTitle(selectedPost.getTitle());
			TextView tv = (TextView) quakeDialog
					.findViewById(R.id.quakeDetailsTextView);
			tv.setText(postPreview);

			break;
		}
	}

}